<?php
class MessagesController extends MessagesAppController {

	var $name = 'Messages';
	var $helpers = array('Html', 'Form', 'Javascript', 'Time');
	var $components = array('Session','RequestHandler','Email');
	var $paginate = array('limit' => 20, 'page' => 1, 'order'=>array('Message.id'=>'desc')); 

	function send($recipientId=null,$recipientType = null,$parentId = null)
	{
		$this->pageTitle = __('Send Message');
		if(!$recipientId || !$recipientType )
		{
			$this->redirect($this->referer());
		}
		if($this->data)
		{
			$this->data['Message']['recipient_id'] =  $recipientId;
			$this->data['Message']['recipient_type'] = $recipientType;
			$this->data['Message']['sender_id'] =  $this->getAuthModel('id');
			$this->data['Message']['sender_type'] = $this->getAuthModel();
			if(!is_null($parentId))
			{
				$this->data['Message']['thread_id'] = $parentId;
			}
			if($this->Message->saveAll($this->data,array('validate'=>'first')))
			{
				$this->successMsg(__('Message has been sent.',true));
				$this->sendMessage($this->Message->getLastInsertID());
				if(!isset($this->params['requested']))
				{
					$this->redirect(array('action'=>'view',$this->Message->getLastInsertId(),'type'=>'sent'));
				}
				return true;
			}
		}
		$this->set(compact('recipientId','recipientType','parentId'));

	}
	
	function view($id = null)
	{
		$this->pageTitle = __("View Message");
		$authedUser = $this->Session->read('Auth.User');
		
		if(!isset($this->params['named']['type']) || !in_array($this->params['named']['type'],array('sent','inbox')))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		$condition = array(); 
		$type = $this->params['named']['type'];
		if($type == 'sent')
		{
			$condition[] = array('Message.sender_id'=>$authedUser['id']);
		}elseif($type == 'inbox')
		{
			$condition[] = array('Message.recipient_id'=>$authedUser['id']);
		}
		$condition[] = array('Message.id'=>$id);
		
		$message = $this->Message->find('first',array('conditions'=>$condition));
		if($this->Message->hasAny(array('id'=>$id)) != true)
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}else if(empty($message))
		{
			$this->warningMsg(__('Please login to view message.'));
			$this->redirect($this->referer());
		}
		/* has_viewed ability is not present in cv core now #6936
		if($message['Message']['recipient_id']==$authedUser['id'] && $message['Message']['has_viewed']==0) {
			$this->Message->saveField('has_viewed',1);
		}*/
		$this->set('isAjax',$this->RequestHandler->isAjax());
		$this->set('message',$message);
		$this->set('type',$this->params['named']['type']);
	}

	function delete($id = null)
	{
		if($this->referer() == '/')
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect('/');
		}
		
		$authedUser = $this->Session->read('Auth.User');
		$fieldToUpdate = 'recipient_deleted';
		if($this->referer() == '/sent_messages')
		{
			$fieldToUpdate = 'sender_deleted';
		}	
		$messageIdsToUpdate = array();
		
		if(!empty($this->data['Message']))
		{
			foreach($this->data['Message'] as $key => $val)
			{
				if($val == 1)
				{
					list($message, $id) = split('_', $key);
					$messageIdsToUpdate[$id] = $id;
				}
			}
		}elseif(!is_null($id))
		{
			$messageIdsToUpdate[$id] = $id;
		}
		
		if(!empty($messageIdsToUpdate))
		{
			$condition[] = array('Message.id'=>$messageIdsToUpdate);
			$this->Message->updateAll(array($fieldToUpdate=>1),array($condition));
			$this->successMsg(__('Message(s) deleted successfully', true));
		}
		else
		{
			$this->errorMsg(__('Please select message(s) to delete', true));
		}		
		$this->redirect($this->referer());
	}
	private function sendMessage($id)
	{
		$message = $this->Message->findById($id);
		$this->prepareEmail();
		$this->Email->to  = $message['Message']['recipient_email'];
		$this->Email->subject = sprintf(__('New Message From %s',true),$message['Message']['sender_username']);
		$this->Email->template = 'new_message';	
		$this->set($message['Message']);
		$this->set('username',$message['Message']['sender_username']);
		$viewLink = Router::url(array('controller'=>'messages','action'=>'view',$message['Message']['id'],'type'=>'inbox'),true);
		$this->set('viewLink',$viewLink);
		$this->Email->send();							
	}

	function index($type= "sent")
 	{
 		$this->paginate['order'] = 'Message.Created DESC';
 		if($type =='inbox')
 		{
 			$this->pageTitle  = 'Inbox';
 			$this->paginate['conditions'] = array('Message.recipient_id'=>$this->getAuthModel('id'),'Message.recipient_type'=>$this->getAuthModel(),'not'=>array('recipient_deleted'=>1));
 		}else
 		{
 			$this->paginate['conditions'] = array('Message.sender_id'=>$this->getAuthModel('id'),'Message.sender_type'=>$this->getAuthModel(),'not'=>array('sender_deleted'=>1));
 		}
 		$title = $type;
 		if($type =='inbox')
 		{
 			$title = 'My Inbox';
 		}else
 		{
 			$title = 'My Sent Messages';
 		}
 		
 		$this->pageTitle  = __($title);
 		$messages = $this->paginate();
 			
 		$this->set('messages',$messages);
 		$this->set('type',$type);
 	}
 	
 	function mark_all_read($userId)
 	{
		Configure::write('debug',0);
		$this->layout = false;
		$result = "false";
 		if($userId && $this->Session->read('Auth.User.id') == $userId) {
			$this->Message->mark_all_read($userId);
			$result = 'true';
 		}
 		echo json_encode($result);
 		Configure::write("debug",0);
 		$this->_stop();
 	}

 	function get_unread_messages_count($userId)
 	{
 		Configure::write('debug',0);
 		$this->layout = false;
 		$result = 0;
 		if($userId)
 		{
 			$result = $this->Message->get_unread_messages_count($userId);
 		}
 		echo json_encode($result);
 		Configure::write("debug",0);
 		$this->_stop();
 	}
 	
 	
 	function read_unread_toggle($userId, $messageId, $markAsRead = true)
 	{
 		if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 		{
 			Configure::write('debug',0);
 			$this->layout = false;
 		}
 		$markAsRead = true;
 			
 		$result = false;
 		if($userId && $messageId)
 		{
 			$messageData = $this->Message->find('first',array('conditions'=>array('Message.id'=>$messageId),'recursive'=>-1));
 			if($messageData)
 			{
 				if($messageData['Message']['sender_id'] == $userId && $messageData['Message']['has_viewed']==true) {
 					$markAsRead = false;
 				} else {
 					$recipientHasViewed = $this->Message->MessageRecipient->find('count',array('conditions'=>array('MessageRecipient.message_id'=>$messageId,'MessageRecipient.recipient_id'=>$userId,'MessageRecipient.has_viewed'=>true),'recursive'=>-1));
 					if($recipientHasViewed>0)
 					{
 						$markAsRead = false;
 					}
 				}
 				
 	 			if($markAsRead)
	 			{
	 				$result = $this->Message->mark_as_readed($userId, $messageData['Message']['parent_id'], $messageId);
	 			} else {
	 				$result = $this->Message->mark_as_unread($userId, $messageId);
	 			}
  			}
 		}
 	 	if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 		{
 			Configure::write('debug',0);
 			$result = (($result)?"1":"0");
 			
 			echo json_encode($result);
 			$this->_stop();
 		}
 		$this->redirect(array('action'=>'index'));
 	}
 	
 	function download ($messageId = null)
 	{
 		if(!$messageId){
 			$this->errorMsg(__('Invalid link for download', true));
 			$this->redirect($this->referer());
 		}
 		$messageData=$this->Message->findById($messageId);
 		if(!$messageData){
 			$this->errorMsg(__('Invalid link for download', true));
 			$this->redirect($this->referer());
 		}
 		
 		$this->view = 'Media';
		$this->autoLayout = false; 
 		
 		$attachmentInfo = pathinfo($messageData['Message']['attachment']['file_url']);
 		$filename = $attachmentInfo['basename'];
 		$params = array
 		(
 				'id' => $attachmentInfo['basename'],
 				'name' => "attachment",
 				'download' => true,
 				'extension' => $attachmentInfo['extension'],
 				'path' => substr($attachmentInfo['dirname'], 1).DS
 		);
 		$this->set($params);
 	}
 	
 	function reply_message($replyToId = null)
 	{
 		if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 		{
 			Configure::write('debug',0);
 			$this->layout = false;
 			if(!$this->Session->read('Auth.User'))
 			{
 				exit;
 			}
 			/*
 			if(empty($this->data))
 			{
 				exit;
 			}
 			*/
 			if(!$replyToId)
 			{
 				exit;
 			}
 		} else {
	 		if(!$this->Session->read('Auth.User'))
	 		{
	 			$this->errorMsg(__('Invalid User!'));
	 			$this->redirect("/");
	 		}
	 		if(!$replyToId)
	 		{
	 			$this->errorMsg(__('Invalid Link!'));
	 			$this->redirect("/");
	 		}
 		}

 		$replyToIdData = $this->Message->findById($replyToId);
 		$currentUsername = $this->Session->read('Auth.User.username');
 		$currentUserId = $this->Session->read('Auth.User.id');
 		$titleText = str_replace($currentUsername, "", str_replace($currentUsername.",", "", str_replace(", ".$currentUsername, "", $replyToIdData['Message']['message_header'])));
 		$this->pageTitle  = __($titleText);
 		
 		if($this->data)
 		{
 			
 			$msgData = $this->data;
 			/*
 			if(!(isset($this->data['Attachment']['name']) && $this->data['Attachment']['name'] && $this->data['Attachment']['error']==0))
 			{
 				unset($msgData['Attachment']);
 			}
 			*/

 			if(isset($msgData['Attachment']['name']) && empty($msgData['Attachment']['name']))
 			{
 				unset($msgData['Attachment']);
 			}
 			
 			$recipients = $replyToIdData['Message']['message_type'];
 			$msgData['Message']['message_type'] = $this->Message->arrange_recipients($recipients,$currentUserId);
 			
 			$msgData['Message']['recipient_type'] = $this->getAuthModel();
 			//$msgData['Message']['recipient_id'] =  $this->Session->read('Auth.User.id');
 			$msgData['Message']['sender_type'] = $this->getAuthModel();
 			$msgData['Message']['sender_id'] =  $currentUserId;
 			$msgData['Message']['body'] =  $this->data['Message']['bodyText'];

 			$msgData['Message']['parent_id'] = $replyToId;
 			$msgData['Message']['has_viewed'] = true;
			$msgData['Message']['to_all_staff'] = $this->Message->has_recipient_all_staff($recipients);
			$msgData['Message']['to_all_client'] = $this->Message->has_recipient_all_client($recipients);
		
			$msgData['MessageRecipient'] = $this->Message->create_recipients($recipients, $currentUserId, $replyToId);
			
 			if($this->Message->saveAll($msgData,array('validate'=>'first')))
 			{
 				$newMessageId = $this->Message->getLastInsertID();
 				$this->sendMessageToAllRecipients($newMessageId);
 				if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 				{
 					exit;
 				} else {
	 				$this->successMsg(__('Message has been sent.',true));
	 				$this->redirect(array('action'=>'index'));  //,'type'=>'inbox'
 				}
 			} else {
 				if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 				{
 					exit;
 				} else {
 					$this->errorMsg(__('Message sending failed.',true));
 				}
 			}
 		}
		
 		$this->Message->mark_as_readed($currentUserId, $replyToId);
 		
 		$this->paginate['order'] = 'Message.Created ASC';
 		$this->paginate['recursive'] = -1;
 		$this->paginate['conditions'] = array('Message.parent_id'=>$replyToId);
 		$messages = $this->paginate();
 		$this->set('msgReplyUrl',$replyToIdData['Message']['replyUrl']);
 		$this->set('replyToIdData',$replyToIdData);
 		$this->set('messages',$messages);
 		$this->set('replyToId',$replyToId);
 	}
 	
 	function create_message() {
 		if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
 		{
 			Configure::write('debug',0);
 			$this->layout = false;
 			if(!$this->Session->read('Auth.User'))
 			{
 				exit;
 			}
 			if(empty($this->data))
 			{
 				exit;
 			}
 		} else {
	 		if(!$this->Session->read('Auth.User'))
	 		{
	 			$this->errorMsg(__('Invalid User!'));
	 			$this->redirect("/");
	  		}
 		}
 		
  		$recipients = array();
  		$prevThreadId = null;
  		if($this->data)
  		{
  			$msgData = $this->data;
  			$senderId = $this->Session->read('Auth.User.id');
  			if($this->data['Message']['recipients'])
  			{
  				$recipients = $this->data['Message']['recipients'];
  				$recipients = $this->Message->remove_duplicate_recipient($recipients, $senderId); //to remove individual selection if group is selected
  				//unset($msgData['Message']['recipients']);
  				//unset($msgData['Message']['bodyText']);
  			}
  			$msgData['Message']['recipient_type'] = $this->getAuthModel();
  			//$msgData['Message']['recipient_id'] =  $this->Session->read('Auth.User.id');
  			$msgData['Message']['sender_type'] = $this->getAuthModel();
  			$msgData['Message']['sender_id'] =  $this->getAuthModel('id');
  			$msgData['Message']['body'] =  $this->data['Message']['bodyText'];
  			
  			if(isset($msgData['Attachment']['name']) && empty($msgData['Attachment']['name']))
  			{
  				unset($msgData['Attachment']);
  			}
  			
  			if(!empty($recipients))
  			{
	  			$prevThreadId = $this->Message->find_previous_thread($senderId,$recipients);
	  			if($prevThreadId)
	  			{
	  				$msgData['Message']['parent_id'] =  $prevThreadId;
	  			}
	  			$msgData['Message']['message_type'] = $this->Message->arrange_recipients($recipients,$senderId);
	  			$msgData['Message']['to_all_staff'] = $this->Message->has_recipient_all_staff($recipients);
	  			$msgData['Message']['to_all_client'] = $this->Message->has_recipient_all_client($recipients);
	  			$msgData['Message']['has_viewed'] = true;
	  			
	  			$msgData['MessageRecipient'] = $this->Message->create_recipients($recipients, $senderId, $prevThreadId);
  			}
  			
			if($this->Message->saveAll($msgData,array('validate'=>'first')))
			{
				$newMessageId = $this->Message->getLastInsertID();
				if(!($prevThreadId))
				{
					$this->Message->id = $newMessageId;
					$this->Message->saveField('parent_id',$newMessageId);
				}
				$this->sendMessageToAllRecipients($newMessageId);
				if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
				{
					exit;
				} else {
					$this->successMsg(__('Message has been sent.',true));
					$this->redirect(array('action'=>'index'));  //,'type'=>'inbox
				}
			} else {
				
				if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
				{
					exit;
				} else {
					$this->errorMsg(__('Message sending failed.',true));
				}
			}
  		}
  		if(isset($this->params['isAjax']) && $this->params['isAjax']==1)
  		{
  			exit;
  		}		
 	}
 	
 	private function sendMessageToAllRecipients($id)
 	{
 		$message = $this->Message->findById($id);
 		$recipients = Set::extract($message['MessageRecipient'],'{n}.recipient_id');
 		//$recipients = $this->Message->MessageRecipient->find('list',array('conditions'=>array('MessageRecipient.message_id'=>$id),'fields'=>array('MessageRecipient.recipient_id'),'recursive'=>-1));
 		if($recipients)
 		{
 			$userObj = Utility::getModelObject('User');
 			foreach($recipients as $recipient)
 			{
 				$user = $userObj->find('first',array('conditions'=>array('User.id'=>$recipient),'fields'=>array('User.username','User.email'),'recursive'=>-1));
 				$this->Email->reset();
		 		$this->prepareEmail();
		 		$this->Email->to  = $user['User']['email'];
		 		$this->Email->subject = sprintf(__('New Message From %s',true),$message['Message']['sender_username']);
		 		$this->Email->template = 'new_message';
		 		$this->set($message['Message']);
		 		$this->set('username',$message['Message']['sender_username']);
		 		//$viewLink = Router::url(array('controller'=>'messages','action'=>'view',$message['Message']['id'],'type'=>'inbox'),true);
		 		$viewLink = Router::url(array('controller'=>'messages','action'=>'index','type'=>'inbox'),true);
		 		$this->set('viewLink',$viewLink);
		 		$this->Email->send();
 			}
 			$this->Email->reset();
 		}
 	}
 	
 	function show_reply_messages_list($replyToId = null)
 	{
		Configure::write('debug',0);
		$this->layout = false;
		if(!$this->Session->read('Auth.User'))
		{
			exit;
		}
		if(!$replyToId)
		{
			exit;
		}
 	
 		$replyToIdData = $this->Message->findById($replyToId);
 		$currentUsername = $this->Session->read('Auth.User.username');
 		$currentUserId = $this->Session->read('Auth.User.id');
 		$titleText = str_replace($currentUsername, "", str_replace($currentUsername.",", "", str_replace(", ".$currentUsername, "", $replyToIdData['Message']['message_header'])));
 		$this->pageTitle  = __($titleText);
 	
 		$this->Message->mark_as_readed($currentUserId, $replyToId);
 			
 		$this->paginate['order'] = 'Message.Created ASC';
 		$this->paginate['recursive'] = -1;
 		$this->paginate['conditions'] = array('Message.parent_id'=>$replyToId);
 		$messages = $this->paginate();
 		$this->set('messages',$messages);
 		$this->set('replyToId',$replyToId);
 	}
 	

}
?>
